package com.example.photo.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

import javax.annotation.PostConstruct;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

@Configuration
public class RestTemplateConfig {

    @Value("${app.domain}")
    public String domain;

    @Value("${app.key}")
    public String key;

    @Value("${app.secret}")
    public String secret;

    public String ticket;

    @PostConstruct
    public void generateTicket() {
        ticket = Base64.getEncoder().encodeToString((key + "." + secret).getBytes(StandardCharsets.UTF_8));
    }

    public HttpHeaders requestOpencenterHeader(){
        HttpHeaders headers = new HttpHeaders();
        headers.set("domain", domain);
        headers.set("ticket", ticket);
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);
        return headers;
    }

    @Bean
    public RestTemplate restTemplate(ClientHttpRequestFactory factory) {
        return new RestTemplate(factory);
    }

    @Bean
    public ClientHttpRequestFactory simpleClientHttpRequestFactory() {
        SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
        factory.setReadTimeout(5000);//单位为ms
        factory.setConnectTimeout(5000);//单位为ms
        return factory;
    }
}